package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: tensquare_parent
 * @description:
 * @author: tianshengfei
 * @create: 2019-12-10 14:43
 **/
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在请求前或者后进行  pre前 post后
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器执行顺序，越小越执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否开启
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器内执行的操作 return任何object的值，都表示放行
     * 不放行setSendZuulReponse设置false，表示不再继续执行
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了");
        //request上下文获取
        RequestContext currentContext = RequestContext.getCurrentContext();
        //request域
        HttpServletRequest request = currentContext.getRequest();
        //网关转发会有两个方法，第一个是options，如果访问失败后面的也不会执行,所以这个方法必须放行
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        //放行登录
        if(request.getRequestURI().indexOf("login")>0){
            return null;
        }

        String header = request.getHeader("Authorization");
        if(header != null &&header.startsWith("Bearer ")){
            String token = header.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                String roles = (String) claims.get("roles");
                if(roles !=null && roles.equals("admin")){
                    //转发头信息
                    currentContext.addZuulRequestHeader("Authorization",token);
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                //不通行
                currentContext.setSendZuulResponse(false);
            }

        }
        currentContext.setSendZuulResponse(false);//终止运行
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
